package com.sunxueqi.framework.security.service;

import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.sunxueqi.common.util.ServletUtils;
import com.sunxueqi.framework.security.LoginUser;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;

@Service
public class ValidatePermissionService {

	@Autowired
	private TokenService tokenService;
	
	/**
	 * 验证当前用户是否有该权限
	 * @param permission 权限字符串
	 * @return 若用户有权限，则返回true，否则返回false
	 */
	public boolean hasPermission(String permission) {
		if(StrUtil.isEmpty(permission)) {
			return false;
		}
		LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
		if(ObjectUtil.isNull(loginUser) || CollectionUtils.isEmpty(loginUser.getPermissions())) {
			return false;
		}
		return hasPermission(loginUser.getPermissions(), permission);
	}

	/**
	 * 判断权限集合是否包含某一项权限
	 * @param permissions 权限集合
	 * @param permission 要判断的权限
	 * @return 若该权限在集合里，则返回true，否则返回false
	 */
	private boolean hasPermission(Set<String> permissions, String permission) {
		return (permissions.contains(permission.trim()));
	}
}
